package plugproxy.util;

import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.HashMap;

/**
 * A simple command line parser.
 *
 * @author Christopher A. Longo (cal@cloud9.net)
 * @version 2.01 11.22.2002 $Revision: 1.3 $
 */
public class CommandLineParser {
    private HashMap<String, String> parameters;  //parameters container

    /**
     * Constructor.  Take an array of String and hashes out the command line
     * options from it.
     *
     * @param args - An array of Strings containing the command line arguments.
     */
    public CommandLineParser(String[] args) {
        parameters = new HashMap<String,String>();
        parseArgs(args);
    }

    /**
     * Returns a parameter passed on the command line.
     *
     * @param param The key for the parameter.
     * @return A String containing the value of the command line parameter.
     */
    public String getParameter(String param) {
        return parameters.get(param);
    }

    /**
     * Tests if a parameter was supplied on the command line.
     * Good for testing switch parameters.
     *
     * @param name The key for the parameter.
     * @return true if the parameter was supplied on the command
     *         line.
     */
    public boolean containsParameter(String name) {
        return parameters.containsKey(name);
    }

    /**
     * Returns a String representation of this object.
     *
     * @return a String representation of this object.
     */
    public String toString() {
        return parameters.toString();
    }

    /**
     * Parses the command line.  Will look for name:value pairs seperated by the
     * characters ':' or '='.  Switches start with the characters '-' or '/'.
     *
     * @param args - An array of Strings containing the command line arguments.
     */
    protected void parseArgs(String[] args) {
        for (String arg : args) {
            StringTokenizer st = new StringTokenizer(arg, "-/:= ");
            while (st.hasMoreTokens()) {
                String name = null;
                String value = null;
                try {
                    name = st.nextToken();
                    value = st.nextToken();
                }
                catch (NoSuchElementException ignore) {
                }
                parameters.put(name, (value == null) ? "true" : value);
            }
        }
    }

}